import os
import time
import pymysql
from docxtpl import DocxTemplate

def createWord(host,user, password, database, port=3309):
    print("开始执行数据字典统计脚本......")

    # 检查数据模版文件是否存在
    if not os.path.exists('input.docx'):
        print("数据模版文件不存在.")
        exit(0)

    # 连接数据库
    db = pymysql.connect(host=host, user=user, password=password, database=database, port=port)
    cursor = db.cursor()

    # 获取所有数据表
    cursor.execute("show tables")
    tablesList = cursor.fetchall()

    tableInfo = []
    nums = 1
    for tablename in tablesList:
        # 获取表结构
        cursor.execute("describe %s" % (tablename[0]))
        tabledes = cursor.fetchall()
        cursor.execute(
            "select table_name, table_comment from information_schema.tables where TABLE_SCHEMA = '%s' and TABLE_NAME = '%s';" % (database,tablename[0]))
        tablecomment = cursor.fetchall()

        cursor.execute(
            "select column_name, column_comment from information_schema.columns where TABLE_SCHEMA = '%s' and TABLE_NAME = '%s';" % (database,tablename[0]))
        comment = cursor.fetchall()

        tableDDl = []
        i = 0
        for colum in tabledes:
            feildDec = comment[i][1]
            is_null = colum[2]
            if is_null == 'NO':
                is_null = 'NOT NULL'
            col_index = colum[3]
            if col_index == 'PRI':
                col_index = 'PRIMARY KEY'
            col_def = colum[4]
            if col_def == None or colum[4] == 'None':
                col_def = ''

            info = {
                'feildName': colum[0],
                'feildType': colum[1],
                'feildIsNull': is_null,
                'feildDef': col_def,
                'feildIndex': col_index,
                'feildDec': feildDec,
            }
            tableDDl.append(info)
            i = i + 1

        tableInfodata = {
            'tableName': tablename[0],
            'tableCnName': tablecomment[0][1],
            'tableType': 'InnoDB',
            'num': nums,
            'tables': tableDDl
        }
        tableInfo.append(tableInfodata)
        nums = nums + 1

    # 读取模版文件
    tpl = DocxTemplate('input.docx')

    # word模版中内容
    context = {
        'time': time.strftime("%Y-%m-%d", time.localtime()),
        'database': database,
        'tableInfo': tableInfo
    }

    print("正在生成doc文件...")
    tpl.render(context)
    tpl.save('%s.docx'%(database))

if __name__ == "__main__":
    print("注意事项:")
    print("请正确输入数据库配置信息")
    print("请将数据模版文件放在执行文件的同级目录下且该目录拥有写入权限")
    host = input('请输入数据库host: ')
    user = input('请输入数据库用户: ')
    password = input('请输入数据库用户密码: ')
    database = input('请输入数据库名称: ')
    port = input('请输入数据库接口号: ')
    createWord(host,user,password,database,int(port))
